#ifndef CHATSERVICE_H
#define CHATSERVICE_H
#include <muduo/net/TcpConnection.h>
#include <functional>
#include "usermodel.hpp"
#include <unordered_map>
#include "json.hpp"
#include "offlinemessagemodel.hpp"
#include"friendmodel.hpp"
#include"groupmodel.hpp"
#include"group.hpp"
#include "redis.hpp"
#include <mutex>
using namespace std;
using namespace placeholders;
using namespace muduo;
using namespace muduo::net;

using json = nlohmann::json;

// 处理消息以及对应的handler回调操作
using msgHandler = function<void(const TcpConnectionPtr &conn, json &js, Timestamp time)>;
class ChatService
{
public:
    // 单例模式
    static ChatService *getInstance();
    void login(const TcpConnectionPtr &conn, json &js, Timestamp time);
    void reg(const TcpConnectionPtr &conn, json &js, Timestamp time);
    void oneChat(const TcpConnectionPtr &conn, json &js, Timestamp time);
    void addFriend(const TcpConnectionPtr &conn, json &js, Timestamp time);
    void loginout(const TcpConnectionPtr &conn, json &js, Timestamp time);
    // 根据消息msgid ，得到对应的方法
    msgHandler getMsgHandler(int msgid);
    // 处理客户端异常退出
    void clientCloseException(const TcpConnectionPtr &conn);
    // 服务器异常退出后，重置状态
    void reset();

    void createGroup(const TcpConnectionPtr &conn, json &js, Timestamp time);
    void addGroup(const TcpConnectionPtr &conn, json &js, Timestamp time);

    void groupChat(const TcpConnectionPtr &conn, json &js, Timestamp time);
    void handleRedisSubscribeMessage(int userid, string msg);


private:
    ChatService();
    unordered_map<int, msgHandler> _msgHandlerMap;
    // 创建一个用户模型对象，用来管理用户信息，操作类对象
    UserModel _userModel;
    OffLineMsgModel _offLineMsgModel;
    FriendModel _friendModel;
    GroupModel _groupModel;
    // 存储在线用户的通信连接 int是id
    unordered_map<int, TcpConnectionPtr> _userConnMap;
    // 定义互斥锁，保证_userConnMap的线程安全
    mutex _connMutex;
    // redis 对象
    Redis _redis;
};
#endif